//
//  QuWeiXunLianMainViewController.swift
//  CKC
//
//  Created by 张振东 on 16/10/5.
//  Copyright © 2016年 ZZD. All rights reserved.
//

import UIKit
import AudioToolbox
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}

class QuWeiXunLianMainViewController: UIViewController,UITextFieldDelegate,UITextViewDelegate {
    
    //获取模拟器的宽度和高度
    let screenWidth = UIScreen.main.bounds.width
    let screenHeight = UIScreen.main.bounds.height
    
    //定义viewController的背景图片
    var backgroundImageView:UIImageView?
    var chaImageView:UIImageView?
    
    //定义自由落体的UILabel和UIImageView对象
    var numberView:UIView?
    var numberLabel:UILabel?
    var feiJiImageView:UIImageView?
    
    //飞机下降的速度
    var speed:CGFloat = 0.5
    var numberFloat:CGFloat?
    
    var textView:UITextView?
    
    //定义一个textField用于存储用户从键盘输入的数字
    var inputNumber:UITextField?
    
    //定义飞机向下运动的垂直距离和水平距离
    var verticalJuLi:CGFloat?
    var horizontalJuLi:CGFloat?

    //定义一个按钮在炮台中间位置
    var faSheZiDanBtn:UIButton?
    
    var daoJiShiTimer:Timer!

    //定义一个爆破ImageView
    var baoPo:UIImageView?
    
    //定义UIProgressBar
    var daoJiShiProgressView:UIProgressView?
    
    //定义一个计时器
    var timer: Timer!
    
    //定义一个Int类型的变量,用于记录答对问题的个数
    var answerCorrectQuestionNumber:Int?
    
    //定义记时结束时,弹出的alertView中显示的字段
    var yongShiLabel:UILabel!
    var timeLabel:UILabel!
    var miaoLabel:UILabel!
    var numberLabels:UILabel!
    var numberValue:UILabel!
    var geLabel:UILabel!
    var answerCorrectNumberLabel:UILabel!
    var answerCorrectNumberValueLabel:UILabel?
    var geShuLabel:UILabel?
    var correctRateLabel:UILabel?
    var correctRateValueLabel:UILabel?
    var speedLabel:UILabel?
    var speedValueLabel:UILabel?
    var shuEveryMinute:UILabel?

    //定义一个Float类型的变量,该变量用于存储正确数
    var correctRate:Float?

    //定义一个Int类型的变量,用于记录产生的问题的总个数
    var allQuestionsNumbers:Int?
    
    //定义一个Float类型的变量,该变量用于存储打字的速度
    var daZiSpeed:Float?
    
    var xuanZhongFenZhongZhi:Int = 0
    
    var remainTime = 120
    
    //定义一个比率
    var biLv:CGFloat?
    
    var dxAlertView:DXAlertView?
    
    override func viewDidLoad() {
        
        self.title = "限时模式"
        answerCorrectQuestionNumber = 0
        allQuestionsNumbers = -1
        self.view.backgroundColor = UIColor(red: 246,green: 246,blue: 246,alpha: 1)
        let leftBarButton = UIButton(frame:CGRect(x: 0,y: 0,width: 20,height: 20))
        leftBarButton.setBackgroundImage(UIImage(named: "fanhui"), for: UIControlState())
        leftBarButton.addTarget(self, action: #selector(backToPrevious), for: .touchUpInside)
        let leftBarButtonItem = UIBarButtonItem(customView: leftBarButton)
        self.navigationItem.leftBarButtonItems = [leftBarButtonItem]
        
        //隐藏导航栏
        self.navigationController?.navigationBar.isHidden = true
        
        if xuanZhongFenZhongZhi == 0{
            remainTime = 120
            biLv = CGFloat(screenHeight)/120
        }else{
            remainTime = xuanZhongFenZhongZhi*60
            biLv = CGFloat(screenHeight)/CGFloat(remainTime)
        }
        
        fengZhuangNextAnimation()
        super.viewDidLoad()
    
    }
    
    func fengZhuangNextAnimation(){
        
        //初始化背景图片
        backgroundImageView = UIImageView(image: UIImage(named: "paotai"))
        backgroundImageView?.frame = CGRect(x: 0,y: 0,width: screenWidth,height: screenHeight)
        self.view.layer.contents = backgroundImageView
        
        //初始化叉图标
        chaImageView = UIImageView(image: UIImage(named: "cha"))
        chaImageView?.frame = CGRect(x: 5,y: 15,width: 20,height: 20)
        //创建JNWSpringAnimation旋转动画
        let rotation = JNWSpringAnimation(keyPath:"transform.rotation")
        rotation?.damping = 6
        rotation?.stiffness = 100
        rotation?.mass = 2
        rotation?.fromValue = 0
        rotation?.toValue = 2
        chaImageView?.layer.add(rotation!, forKey: rotation?.keyPath)
        chaImageView?.transform = CGAffineTransform(rotationAngle: CGFloat(2))
        
        
        //给chaImageView添加手势
        let chaGesture = UITapGestureRecognizer(target: self,action: #selector(chaImageViewGesture))
        chaImageView?.addGestureRecognizer(chaGesture)
        chaImageView?.isUserInteractionEnabled = true

        //初始化numberView
        let number = arc4random_uniform(200)
        numberFloat = CGFloat(number)
        numberView = UIView(frame:CGRect(x: numberFloat!,y: 0,width: 40,height: 40))
        numberView?.layer.borderWidth = 2
        numberView?.layer.borderColor = UIColor.brown.cgColor
        
        
        //创建JNW实例
        let scale = JNWSpringAnimation(keyPath:"transform.translation.y")
        scale?.damping = 6
        scale?.stiffness = 1
        scale?.mass = 200
        //设置初始值
        scale?.fromValue = 0
        scale?.toValue = screenHeight*2
        scale?.speed = Float(speed)
        //为scale的层添加动画
        numberView?.alpha = 1.0
        
        numberView?.layer.add(scale!, forKey: scale?.keyPath)
        //更新numberLabel的动画设置值
        numberView?.transform = CGAffineTransform(translationX: 0,y: screenHeight*2)
        //初始化UILabel
        numberLabel = UILabel(frame:CGRect(x: (40-30)/2,y: (40-30)/2,width: 30,height: 30))
        numberLabel?.text = "\(number)"
        numberLabel?.textAlignment = .center
        numberLabel?.layer.cornerRadius = 15
        
        
        //初始化feiJiImageView对象
        feiJiImageView = UIImageView(image: UIImage(named: "feiji"))
        feiJiImageView?.frame = CGRect(x:numberFloat!+40,y:0,width:40,height:40)
        
        //feiJiImageView添加动画
        feiJiImageView?.layer.add(scale!, forKey: scale?.keyPath)
        feiJiImageView?.transform = CGAffineTransform(translationX: 0, y: screenHeight*2)
        
        //初始化textView
        textView = UITextView(frame: CGRect(x: 0, y: 120, width: self.view.bounds.size.width, height: 0))
        textView?.delegate = self
        textView?.text = ""
        textView?.becomeFirstResponder()
        textView?.keyboardType = .phonePad
        
        //初始化用户输入的textField
        inputNumber = UITextField(frame: CGRect(x:numberFloat!,y:40,width:40,height:25))
        inputNumber?.backgroundColor = UIColor.red
        //        inputNumber?.layer.borderWidth = 1
        inputNumber?.borderStyle = .line
        inputNumber?.isEnabled = true
        inputNumber?.becomeFirstResponder()
        inputNumber?.keyboardType = .numberPad
        
        inputNumber?.layer.add(scale!, forKey: scale?.keyPath)
        inputNumber?.transform = CGAffineTransform(translationX: 0, y: screenHeight*2)
        
        //初始化发射子弹按钮
        faSheZiDanBtn = UIButton(frame:CGRect(x: screenWidth/2-10,y: screenHeight/2-10,width: 26,height: 46))
        faSheZiDanBtn?.setImage(UIImage(named: "zidan"), for: UIControlState())
        //刚开始子弹是不显示的
        faSheZiDanBtn?.isUserInteractionEnabled = false
        faSheZiDanBtn?.isHidden = true

        
        //初始化爆破ImageView
        baoPo = UIImageView(image: UIImage(named: "baozha"))
        baoPo?.isHidden = true
        
        //初始化UIProgressView对象
        daoJiShiProgressView = UIProgressView(frame:CGRect(x: 0,y: 0,width: screenWidth,height: 2))
        //进度条刚开始完整显示
        daoJiShiProgressView?.progress = 1.0
        //进度条的颜色
        daoJiShiProgressView?.progressTintColor = UIColor.blue
        //进度条的轨迹颜色
        daoJiShiProgressView?.trackTintColor = UIColor.green
        
        //问题总数加加1
        allQuestionsNumbers! += 1
        print(allQuestionsNumbers as Any)
        
        //倒计时
        timers()
        self.numberView?.addSubview(numberLabel!)
        self.view.addSubview(backgroundImageView!)
        self.view.addSubview(chaImageView!)
        self.view.addSubview(numberView!)
        self.view.addSubview(feiJiImageView!)
        self.view.addSubview(textView!)
        self.view.addSubview(inputNumber!)
        self.view.addSubview(faSheZiDanBtn!)
        self.view.addSubview(baoPo!)
        self.view.addSubview(daoJiShiProgressView!)
    }
    
    
    //点击该imageView时,返回到上一个页面
    func chaImageViewGesture(){
        self.navigationController?.popViewController(animated: true)
    }
    
    
    func textViewDidChange(_ textView: UITextView) {
        
        print(textView.text)
        //用户从键盘输入的值传递到textField中
        inputNumber?.text = textView.text
        
        if xuanZhongFenZhongZhi == 0{
            verticalJuLi = speed * CGFloat((120-remainTime))
            print(speed)
            print(remainTime)
        }else{
            verticalJuLi = speed * CGFloat((xuanZhongFenZhongZhi*60-remainTime))
            print(speed)
            print(remainTime)
            print(verticalJuLi as Any)
        }
        
        horizontalJuLi = numberFloat
            //判断用户输入的字符串是否和numberFloat一样,如果一样,那么发射子弹,否则允许用户一直输入
            //将inputNumber.text转换为Int
            if let inputNumber = inputNumber?.text{
                let inputNumberInt = Int(inputNumber)
                //将随机生成的数字转换成Int类型
                if let numberFloat = numberLabel?.text{
                    let numberFloatInt = Int(numberFloat)
                    print(numberFloatInt as Any)
                    //当用户输入的数值与随机生成的数值相同时
                    if inputNumberInt == numberFloatInt{
                        
                        print(verticalJuLi as Any)
                        print(horizontalJuLi as Any)
                        
                        //子弹图片具有交互性,并且子弹图片可以显示
                        faSheZiDanBtn?.isUserInteractionEnabled = true
                        faSheZiDanBtn?.isHidden = false
                        let endPoint = CGPoint(x: horizontalJuLi!+40+20, y: verticalJuLi!+40)
                        UIView.animate(withDuration: 0.6, animations: {
                            var rect = CGRect(x: self.screenWidth/2, y: self.screenHeight/2, width: 4, height: 24)
                            rect.origin = endPoint
                            self.faSheZiDanBtn?.frame = rect
                            
                        }) 
                        daoJiShiTimer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(xianShiBaoPoAnimation), userInfo: nil, repeats: true)
                        
                    }else if(textView.text.characters.count < numberLabel?.text?.characters.count){
                        print("您输入的数值与显示的值不一致!!")
                        //获取numberLabel.text字符串的长度
                        let stringCount = Int((numberLabel?.text?.characters.count)!)
                        //如果输入的字符串的长度小于随机生成的数字的长度,那么就一直赋值
                        for index in 0...stringCount-1{
                            print(index)
                            self.inputNumber!.text = textView.text
                        }
                        
                        
                    }else if (Int(textView.text) != numberFloatInt){
                        print(Int(textView.text) as Any)
                        //弹出警告框,显示用户输入错误
                        let alertView = UIAlertView(frame:CGRect(x: (screenWidth-screenWidth/4)/2,y: (screenHeight-screenHeight/4)/2,width: screenWidth/4,height: screenHeight/4))
                        alertView.title = "提醒"
                        alertView.delegate = self
                        alertView.message = "您好,您输入的数值与显示的值不一致!!"
                        alertView.addButton(withTitle: "下一题")
                        alertView.show()
                        //将文本置空
                        textView.text = ""
                        //飞机以及输入框等控件让其消失
                        self.feiJiImageView?.removeFromSuperview()
                        self.numberLabel?.removeFromSuperview()
                        self.numberView?.removeFromSuperview()
                        self.inputNumber?.removeFromSuperview()
                        self.faSheZiDanBtn?.removeFromSuperview()
                        //消失之后开始下一轮
                        fengZhuangNextAnimation()
                        //键盘成为第一响应者
                        textView.becomeFirstResponder()
                        //键盘为iPhone数字键盘
                        textView.keyboardType = .phonePad
                    }
                    
                }
            }
    }

  
    /*
     时间:2016-7-30
     作者:张振东
     功能:实现当子弹和飞机相撞的时候,所有的控件全部消失
     */
    func xianShiBaoPoAnimation(){
            //正确数+1
            answerCorrectQuestionNumber! += 1
            
            print(answerCorrectQuestionNumber as Any)
            baoPo?.frame = CGRect(x:numberFloat!+40,y:self.verticalJuLi!*biLv!,width:30,height:30)
            UIView.animate(withDuration: 1, animations: {
                self.baoPo?.isHidden = false
                self.baoPo?.alpha = 0
                }, completion: { (true) in
                    
            }) 
        
            //在这里播放系统声音
            let systemSoundUrl = Bundle.main.url(forResource: "baoposound", withExtension: "WAV")
            var systemSoundId:SystemSoundID = 0
            //生成该资源对应的id
            AudioServicesCreateSystemSoundID(systemSoundUrl! as CFURL, &systemSoundId)
            //播放音乐
            AudioServicesPlaySystemSound(systemSoundId)
            print("这时候子弹和飞机相交了,则此时显示飞机坠毁的画面")
            
            self.feiJiImageView?.removeFromSuperview()
            self.numberLabel?.removeFromSuperview()
            self.numberView?.removeFromSuperview()
            self.inputNumber?.removeFromSuperview()
            self.faSheZiDanBtn?.removeFromSuperview()
            //timer.invalidate()
            if daoJiShiTimer != nil{
                daoJiShiTimer.invalidate()
                daoJiShiTimer = nil
            }
        
            //推迟1秒执行
            let time: TimeInterval = 0.5
            let delay = DispatchTime.now() + Double(Int64(time * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
            DispatchQueue.main.asyncAfter(deadline: delay) {
                self.fengZhuangNextAnimation()
                //当从新生成飞机、UITextfield、inputNumber时,让textView重新获得焦点
                self.textView?.isUserInteractionEnabled = true
                self.textView?.becomeFirstResponder()
                self.textView?.keyboardType = .phonePad
            }
        
        }

    //倒计时功能
    func timers(){
        if timer != nil{
            timer.invalidate()
            timer = nil
        }
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerAction), userInfo: nil, repeats:true)
    }

    func timerAction(){
        if(remainTime < 0){
            getCorrectRate()
            //倒计时结束
            timer.invalidate()
            remainTime = xuanZhongFenZhongZhi*60
            dxAlertView?.isHidden = true
            
        }else {
            remainTime = remainTime - 1
            if xuanZhongFenZhongZhi == 0{
                let progressValue = Float(remainTime)/120
                daoJiShiProgressView!.setProgress(progressValue, animated:false)
            }else{
                let progressValue = Float(remainTime)/Float(xuanZhongFenZhongZhi*60)
                daoJiShiProgressView!.setProgress(progressValue, animated:false)
            }
        }
    }

    /*
     该方法用于计算成功爆破飞机的个数
     */
    @discardableResult
    func getCorrectRate() -> Float{
        correctRate = Float(answerCorrectQuestionNumber!)/Float(allQuestionsNumbers!)
        print(correctRate as Any)
        //创建用时UIlabel对象
        yongShiLabel = UILabel(frame:CGRect(x: 10,y: 35,width: 30,height: 30))
        fengZhuangLabelAttributes(yongShiLabel!)
        
        //创建UIlabel对象
        timeLabel = UILabel(frame:CGRect(x: 45,y: 35,width: 30,height: 30))
        fengZhuangLabelAttributes(timeLabel!)
        
        //创建秒UIlabel对象
        miaoLabel = UILabel(frame:CGRect(x: 80,y: 35,width: 30,height: 30))
        fengZhuangLabelAttributes(miaoLabel!)
        
        //创建数量UIlabel
        numberLabels = UILabel(frame:CGRect(x: 10,y: 55,width: 30,height: 30))
        fengZhuangLabelAttributes(numberLabels!)
        
        //创建数量值UIlabel
        numberValue = UILabel(frame:CGRect(x: 45,y: 55,width: 30,height: 30))
        fengZhuangLabelAttributes(numberValue!)
        
        //创建个UILabel
        geLabel = UILabel(frame:CGRect(x: 80,y: 55,width: 30,height: 30))
        fengZhuangLabelAttributes(geLabel!)
        
        //创建答对数UIlabel
        answerCorrectNumberLabel = UILabel(frame:CGRect(x: 115,y: 50,width: 50,height: 40))
        fengZhuangLabelAttributes(answerCorrectNumberLabel!)
        
        //创建答对数值UIlabel
        answerCorrectNumberValueLabel = UILabel(frame:CGRect(x: 160,y: 60,width: 20,height: 20))
        fengZhuangLabelAttributes(answerCorrectNumberValueLabel!)
        
        //创建个UIlabel
        geShuLabel = UILabel(frame:CGRect(x: 195,y: 60,width: 20,height: 20))
        fengZhuangLabelAttributes(geShuLabel!)
        
        //创建正确率UIlabel
        correctRateLabel = UILabel(frame:CGRect(x: 10,y: 70,width: 50,height: 40))
        fengZhuangLabelAttributes(correctRateLabel!)
        
        //创建正确率值UILabel
        correctRateValueLabel = UILabel(frame:CGRect(x: 55,y: 70,width: 40,height: 40))
        fengZhuangLabelAttributes(correctRateValueLabel!)
        
        //创建速度UIlabel
        speedLabel = UILabel(frame:CGRect(x: 115,y: 74,width: 30,height: 30))
        fengZhuangLabelAttributes(speedLabel!)
        
        //创建速度值TextLabel
        speedValueLabel = UILabel(frame:CGRect(x: 150,y: 74,width: 30,height: 30))
        fengZhuangLabelAttributes(speedValueLabel!)
        
        //创建数每分钟单位UIlabel
        shuEveryMinute = UILabel(frame:CGRect(x: 185,y: 70,width: 50,height: 40))
        fengZhuangLabelAttributes(shuEveryMinute!)
        
        dxAlertView = DXAlertView(title: "限时模式", contentText: "", leftButtonTitle: "再试一次", rightButtonTitle: "返回")
        dxAlertView!.addSubview(yongShiLabel!)
        dxAlertView!.addSubview(timeLabel!)
        dxAlertView!.addSubview(miaoLabel!)
        dxAlertView!.addSubview(numberLabels!)
        dxAlertView!.addSubview(numberValue!)
        dxAlertView!.addSubview(geLabel!)
        dxAlertView!.addSubview(answerCorrectNumberLabel!)
        dxAlertView!.addSubview(answerCorrectNumberValueLabel!)
        dxAlertView!.addSubview(geShuLabel!)
        dxAlertView!.addSubview(correctRateLabel!)
        dxAlertView!.addSubview(correctRateValueLabel!)
        dxAlertView!.addSubview(speedLabel!)
        dxAlertView!.addSubview(speedValueLabel!)
        dxAlertView!.addSubview(shuEveryMinute!)
        dxAlertView!.show()
        
        return correctRate!

    }
    
    
    /*
     时间:2016-8-3
     作者:张振东
     功能:该方法用于封装UIlabel的一些属性
     */
    @discardableResult
    func fengZhuangLabelAttributes(_ label:UILabel) -> UILabel{
        label.font = UIFont.systemFont(ofSize: 12)
        switch label {
        case yongShiLabel!:
            yongShiLabel!.text = "用时:"
        case timeLabel!:
            if xuanZhongFenZhongZhi == 0{
                timeLabel!.text = "120"
                biLv = CGFloat(screenHeight)/120
            }else{
                timeLabel!.text = "\(xuanZhongFenZhongZhi)*60"
                
            }

            timeLabel.textColor = UIColor.red
        case miaoLabel!:
            miaoLabel!.text = "秒"
        case numberLabels!:
            numberLabels!.text = "数量:"
        case numberValue!:
            if let allQuestionsNumbers = allQuestionsNumbers{
                print(allQuestionsNumbers)
                numberValue!.text = "\(allQuestionsNumbers)"
            }
            numberValue.textColor = UIColor.red
            
        case geLabel!:
            geLabel!.text = "个"
        case answerCorrectNumberLabel!:
            answerCorrectNumberLabel!.text = "答对数:"
        case answerCorrectNumberValueLabel!:
            if let answerCorrectQuestionNumber = answerCorrectQuestionNumber{
                print(answerCorrectQuestionNumber)
                answerCorrectNumberValueLabel!.text = "\(answerCorrectQuestionNumber)"
            }
            answerCorrectNumberValueLabel?.textColor = UIColor.red
        case geShuLabel!:
            geShuLabel!.text = "个"
        case correctRateLabel!:
            correctRateLabel!.text = "正确率:"
        case correctRateValueLabel!:
            if let correctRate = correctRate{
                print(correctRate)
                let correctRatePercentage = correctRate*100
                correctRateValueLabel!.text = "\(correctRatePercentage)"+"%"
            }
            correctRateValueLabel?.textColor = UIColor.red
        case speedLabel!:
            speedLabel!.text = "速度:"
        case speedValueLabel!:
            
            daZiSpeed = Float(allQuestionsNumbers!/2)
            print(daZiSpeed as Any)
            let daZiSpeedInt = Int(daZiSpeed!)
            print(daZiSpeedInt)
            speedValueLabel?.text = "\(daZiSpeedInt)"
            speedValueLabel?.textColor = UIColor.red
        case shuEveryMinute!:
            shuEveryMinute?.text = "数/分钟"
            
        default:
            print("22222")
        }
        return label
        
    }

    //返回到上一个页面
    func backToPrevious(){
        if timer != nil{
            timer.invalidate()
            timer = nil
        }
        dxAlertView?.isHidden = true
        self.navigationController?.popViewController(animated: true)
    }

    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
